package com.aixin.project.servlet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.Template;
import org.apache.velocity.context.Context;

import com.aixin.project.data.User;
import com.aixin.project.handler.UserHandler;
import com.aixin.project.util.RequestUtil;

public class SignupServlet extends BaseServlet {

    @Override
    protected Template execute(HttpServletRequest request,
                               HttpServletResponse response, Context ctx) {
        String method = RequestUtil.getStr(request, "method", null);
        if (method == null) return getTemplate("signup.vm");
        String username = RequestUtil.getStr(request, "username", null);
        String password = RequestUtil.getStr(request, "password", null);
        password = RequestUtil.toMD5(password);
        String school = RequestUtil.getStr(request, "school", null);
        String contactor = RequestUtil.getStr(request, "contactor", null);
        String contactstyle = RequestUtil.getStr(request, "contactstyle", null);
        String email = RequestUtil.getStr(request, "email", null);
        if (username != null && password != null && school != null && contactor != null && contactstyle != null && email != null) {
            User user = new User(username, password,school, contactor, contactstyle, email);
            long uid = UserHandler.insert(user);
            if (uid > 0) {
                /*don't automatic login*/
/*                user.setId(uid);
                RequestUtil.setCookie("u", "u_" + uid, CommonConstants.COOKIE_AGE, "/", response);
                AxMemcached.set(CommonConstants.MKEY_USER + uid, user);
                AxSession axsession = new AxSession(UserType.USER, uid, false);
                request.getSession().setAttribute(CommonConstants.USER_SESSION, axsession);*/
                request.getSession().setAttribute("MESSAGE","恭喜你注册成功,请耐心等待工作人员审核.");
            }else{
                request.getSession().setAttribute("MESSAGE","对不起,注册失败,请重新注册或者与我们的工作人员联系");
            }
            this.sendRedirect(response, "/");
            return null;
        }else{
            return getTemplate("signup.vm");
        }
    }
}
